#!/usr/bin/env python3
"""
MCP审查处理器
统一管理各种代码审查工具
"""

from typing import Dict, Any, List
import logging

from biz.mcp.tools.code_review import CodeReviewTool
from biz.mcp.tools.branch_review import BranchReviewTool
from biz.mcp.tools.complexity_review import ComplexityReviewTool
from biz.mcp.tools.directory_review import DirectoryReviewTool
from biz.mcp.tools.mysql_review import MySQLReviewTool

logger = logging.getLogger(__name__)


class ReviewHandler:
    """
    审查处理器
    统一管理和调度各种代码审查工具
    """
    
    def __init__(self):
        # 初始化各种审查工具
        self.tools = {
            "code_review": CodeReviewTool(),
            "branch_review": BranchReviewTool(),
            "complexity_review": ComplexityReviewTool(),
            "directory_review": DirectoryReviewTool(),
            "mysql_review": MySQLReviewTool(),
        }
        
        # 工具描述信息
        self.tool_schemas = [
            {
                "name": "code_review",
                "description": "基于GitLab分支的代码审查，分析代码变更并提供改进建议",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "gitlab_url": {
                            "type": "string",
                            "description": "GitLab项目URL或分支URL"
                        },
                        "branch_name": {
                            "type": "string",
                            "description": "要审查的分支名称（可选，如果URL中包含分支信息）"
                        }
                    },
                    "required": ["gitlab_url"]
                }
            },
            {
                "name": "branch_review",
                "description": "GitLab分支命名规范审查，评估分支命名的规范性",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "gitlab_url": {
                            "type": "string",
                            "description": "GitLab项目URL或分支URL"
                        },
                        "branch_name": {
                            "type": "string",
                            "description": "要审查的分支名称（可选，如果URL中包含分支信息）"
                        }
                    },
                    "required": ["gitlab_url"]
                }
            },
            {
                "name": "complexity_review",
                "description": "代码复杂度分析，识别高复杂度函数并提供优化建议",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "directory": {
                            "type": "string",
                            "description": "要分析的项目根目录路径"
                        },
                        "top_n": {
                            "type": "integer",
                            "description": "显示复杂度最高的N个函数（默认10）",
                            "default": 10
                        }
                    },
                    "required": ["directory"]
                }
            },
            {
                "name": "mysql_review",
                "description": "MySQL数据库表结构设计审查和性能优化建议",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "host": {
                            "type": "string",
                            "description": "数据库主机地址（默认localhost）",
                            "default": "localhost"
                        },
                        "port": {
                            "type": "integer",
                            "description": "数据库端口（默认3306）",
                            "default": 3306
                        },
                        "user": {
                            "type": "string",
                            "description": "数据库用户名（默认root）",
                            "default": "root"
                        },
                        "password": {
                            "type": "string",
                            "description": "数据库密码"
                        },
                        "database": {
                            "type": "string",
                            "description": "数据库名称"
                        },
                        "pattern": {
                            "type": "string",
                            "description": "表名通配符 (支持LIKE语法，如 user%、log_%)，留空表示全部表",
                            "default": ""
                        }
                    },
                    "required": ["password", "database"]
                }
            },
            {
                "name": "directory_review",
                "description": "项目目录结构审查，评估目录组织的规范性和可维护性",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "directory": {
                            "type": "string",
                            "description": "要审查的项目根目录路径"
                        },
                        "language": {
                            "type": "string",
                            "description": "项目开发语言",
                            "enum": ["python", "java", "php", "vue"]
                        },
                        "max_depth": {
                            "type": "integer",
                            "description": "目录遍历最大深度（默认3）",
                            "default": 3
                        },
                        "only_dirs": {
                            "type": "boolean",
                            "description": "是否只显示目录结构（默认false）",
                            "default": False
                        }
                    },
                    "required": ["directory", "language"]
                }
            }
        ]
    
    def list_tools(self) -> List[Dict[str, Any]]:
        """
        获取所有可用工具的列表
        """
        return self.tool_schemas
    
    async def call_tool(self, name: str, arguments: Dict[str, Any]) -> str:
        """
        调用指定的工具
        """
        try:
            if name not in self.tools:
                return f"错误: 未知的工具 '{name}'"
            
            logger.info(f"调用工具: {name}，参数: {arguments}")
            
            # 执行工具
            tool = self.tools[name]
            result = await tool.execute(arguments)
            
            logger.info(f"工具 {name} 执行完成")
            return result
            
        except Exception as e:
            error_msg = f"工具 '{name}' 执行失败: {str(e)}"
            logger.error(error_msg, exc_info=True)
            return error_msg
    
    def get_tool_info(self, name: str) -> Dict[str, Any]:
        """
        获取指定工具的详细信息
        """
        for tool in self.tool_schemas:
            if tool["name"] == name:
                return tool
        return {}
    
    def validate_tool_arguments(self, name: str, arguments: Dict[str, Any]) -> tuple[bool, str]:
        """
        验证工具参数
        """
        tool_schema = None
        for tool in self.tool_schemas:
            if tool["name"] == name:
                tool_schema = tool["inputSchema"]
                break
        
        if tool_schema is None:
            return False, f"未知的工具: {name}"
        
        required_fields = tool_schema.get("required", [])
        
        # 检查必需字段
        for field in required_fields:
            if field not in arguments:
                return False, f"缺少必需参数: {field}"
        
        # 检查字段类型（简单验证）
        properties = tool_schema.get("properties", {})
        for field, value in arguments.items():
            if field in properties:
                expected_type = properties[field].get("type")
                if expected_type == "string" and not isinstance(value, str):
                    return False, f"参数 {field} 应为字符串类型"
                elif expected_type == "integer" and not isinstance(value, int):
                    return False, f"参数 {field} 应为整数类型"
                elif expected_type == "boolean" and not isinstance(value, bool):
                    return False, f"参数 {field} 应为布尔类型"
        
        return True, "参数验证通过"